<template>
    <div class="outPutStatistics">
        <dynamic-form :formDataList="formDataList" @getFormData='getFormData'></dynamic-form>
        <!-- 按钮操作 -->
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline"
                        @click="createUser('createUser')">新增用户</el-button>
                    <el-button type="primary" size="mini" icon="el-icon-download" plain @click='importModel'>导入
                    </el-button>
                    <el-button type="primary" size="mini" icon="el-icon-upload2" plain @click='getUserExport'
                        :disabled='disabled'>导出</el-button>
                    <el-button type="text" size="mini" icon="el-icon-document" @click="viewImportLog">查看导入日志</el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'></pop-checkbox>
                </div>
            </template>
        </custom-setbtn>

        <!-- 表格 -->
        <tableList :tableGroup='tableGroup' @tableListChecked='tableListChecked' @tableSet='tableSet'
            @webPermission='webPermission' :searchForm='formDataList.searchForm' ref='tableList' @mobilePermission='emitPermission'
            @exportDisabled='exportDisabled' @defaultPassWord='defaultPassWord'
            @createSuccess='createSuccess'>
        </tableList>

        <!-- 新增用户 -->
        <common-dialog ref='createUser' :width="784" @close='dialogClose("createUser", "createForm")'>
            <template #title>
                <span class="title">{{ createrUserTitle}}</span>
            </template>
            <template #body>
                <div class='dialogBody clearfix'>
                    <div class='formArea_user'>
                        <el-form :model="createForm" ref="createForm" label-width="120px" size="mini"
                            :rules='form_userRules' :hide-required-asterisk="true">
                            <el-form-item prop='account'>
                                <template slot='label'>
                                    <span style="color: red">*</span>
                                    账号
                                </template>
                                <el-input v-model="createForm.account" placeholder="请填写"></el-input>
                            </el-form-item>
                            <el-form-item prop='name'>
                                <template slot='label'>
                                    <span style="color: red">*</span>
                                    姓名
                                </template>
                                <el-input v-model="createForm.name" placeholder="请填写"></el-input>
                            </el-form-item>
                            <el-form-item prop='mobile' label='手机号'>
                                <el-input v-model="createForm.mobile" placeholder="请填写" :maxlength="120"></el-input>
                            </el-form-item>
                            <el-form-item prop='role'>
                                <template slot='label'>
                                    <span style="color: red">*</span>
                                    角色
                                </template>
                                <el-select v-model="createForm.role" multiple filterable remote reserve-keyword
                                    placeholder="请选择" :remote-method="remoteMethod_role" :loading="loading"
                                    @focus='getFocus("role")' :disabled='roleFlag'>
                                    <el-option v-for="item in roleItems.options" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop='depName' label='部门名称'>
                                <el-select v-model="createForm.depName" multiple filterable remote reserve-keyword
                                    placeholder="请选择" :remote-method="remoteMethod_dep" :loading="selLoading"
                                    @focus='getFocus("dep")'>
                                    <el-option v-for="item in depItems.options" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item  label='虚拟用户'>
                                <el-select v-model="createForm.virtualType" filterable placeholder="请选择" @change="virtualUserChange" ref="virtual">
                                    <el-option v-for="item in isVirtualUserOptions" :key="item.value"
                                        :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <!-- ====================自定义==================== -->
                            <el-form-item
                                v-for='(item, i) in customFiledList'
                                :key="i" 
                                :label='item.chineseName'
                                :prop="item.id"
                                v-show='hiddenRule(item)'
                            >
                                <el-checkbox-group v-show="false" v-model="createForm[item.id]"></el-checkbox-group>
                                <template slot='label'>
                                    <span style="color: red" v-show="requireRsterisk(item)">*</span>
                                    {{ item.chineseName }}
                                    <el-tooltip class="item" effect="dark" :content="item.tips" placement="top" v-show='item.tips'>
                                        <span class="iconfont icon-wenhao wenhao"></span>
                                    </el-tooltip>
                                </template>
                                <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData" @uploadProgress='uploadProgress' ref='formLibrary'></formLibrary>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </template>
            <template #footer>
                <el-button size="mini" @click='closeDialog("createUser", "createForm")'>取 消</el-button>
                <el-button type="primary" size="mini" @click='dialogOk("createUser", "createForm")'>确 定</el-button>
            </template>
        </common-dialog>

        <!-- 新增成功 -->
        <common-dialog ref='newUser' :width="416" class='newOkBox'>
            <template #title>
                <span class='el-icon-circle-check newSuccess'></span>
                新建用户成功
            </template>
            <template #body>
                <p>账号: {{ newSuccessData.user }}</p>
                <p>姓名: {{ newSuccessData.name }}</p>
                <p>密码: {{ newSuccessData.pwd }}</p>
            </template>
            <template #footer>
                <el-button type="primary" size="mini" @click='newSuccess("newUser")'>知道了</el-button>
            </template>
        </common-dialog>

        <!-- 重置密码 -->
        <common-dialog ref='newPwd' :width="570" @close='dialogClose("newPwd", "resetPwd")'>
            <template #title>
                <span class="title">重置密码</span>
            </template>
            <template #body>
                <div class='dialogBody_newpwd clearfix'>
                    <div class=''>
                        <el-form :model="resetPwd" ref="resetPwd" label-width="80px" size="mini" :rules='form_pwdRules'>
                            <el-form-item label="姓名" prop='name'>
                                <el-input v-model="resetPwd.name" placeholder="请填写" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="账号" prop='account'>
                                <el-input v-model="resetPwd.account" placeholder="请填写" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="新密码" prop='xmm'>
                                <el-input v-model="resetPwd.xmm" placeholder="请输入新密码" type='password' show-password>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="确认密码" prop='qrmm'>
                                <el-input v-model="resetPwd.qrmm" placeholder="请输入新密码" type='password' show-password>
                                </el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </template>
            <template #footer>
                <el-button size="mini" @click='closeDialog("newPwd", "resetPwd")'>取 消</el-button>
                <el-button type="primary" size="mini" @click='dialogOk("newPwd", "resetPwd")'>确 定</el-button>
            </template>
        </common-dialog>

        <!-- web端权限 -->
        <common-dialog ref='webPermission' :width="890" v-loading="webPermissionLoading" element-loading-text="加载中"
            element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading">
            <template #title>
                <span class="title">WEB端权限设置</span>
            </template>
            <template #body>
                <div class='webPermission'>
                    <p>配置用户 系统管理员 权限：</p>
                    <div class='checkGroup_permission'>
                        <el-row>
                            <el-col :span="8">
                                <div class='menu_item'>
                                    <div class='menu_th'>
                                        <span>一级菜单</span>
                                    </div>
                                    <div class='menu_tb'>
                                        <div :class="['menu_tb_list',index == activeIndex ? 'active' : '']"
                                            v-for='(item,index) in projectFormBatch' :key='item.permCode'
                                            @click='getSubmenu(item.submenu,index)'>
                                            <el-checkbox v-model="item.blPerm" :ref='item.permCode'
                                                :indeterminate="menuIsIndeterminate"
                                                @change='firstMenuChange(item)'>
                                                <span @click.prevent=''>{{item.permTitle}}</span>
                                            </el-checkbox>
                                            <span class='tag el-icon-arrow-right'></span>
                                        </div>
                                    </div>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class='menu_item'>
                                    <div class='menu_th'>
                                        <span>二级菜单</span>
                                    </div>
                                    <div class='menu_tb'>
                                        <template v-show='submenu.length'>
                                            <div class="menu_tb_list" :class="{active:item.filtrateConfig}"
                                                v-for='(item,index) in submenu' :key='item.permCode'>
                                                <el-checkbox v-model="item.blPerm" @change='checkChange(item,index)'
                                                    >
                                                    <span @click.prevent=''>{{item.permTitle}}</span>
                                                </el-checkbox>
                                                <span class='tag el-icon-arrow-right'
                                                    v-if="item.filtrateConfig"></span>
                                            </div>
                                        </template>
                                        <el-empty description="暂无数据" :image-size='100' v-show='!submenu.length'>
                                        </el-empty>
                                    </div>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class='menu_item'>
                                    <div class='menu_th'>
                                        <span>筛选配置</span>
                                    </div>
                                    <div class='menu_tb' v-show='config_btn.length'>
                                        <div class="menu_tb_list config">
                                            <span>表单配置</span>
                                            <el-checkbox v-model="config_checkAll"
                                                :indeterminate="config_isIndeterminate" @change="handleCheckAllChange">
                                                全选</el-checkbox>
                                        </div>
                                        <div class="menu_tb_list_group">
                                            <el-checkbox-group v-model="config_group" @change="handleCheckedConfig">
                                                <el-checkbox v-for="item in config_btn" :label="item.permCode"
                                                    :key="item.permCode">
                                                    {{item.permTitle}}
                                                </el-checkbox>
                                            </el-checkbox-group>
                                        </div>
                                    </div>
                                    <div class='menu_tb' v-show='!config_btn.length'>
                                        <el-empty description="暂无数据" :image-size='100'></el-empty>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </template>
            <template #footer>
                <el-button size="mini" @click="$refs['webPermission'].closeDialog(),activeIndex = 0">取 消</el-button>
                <el-button type="primary" size="mini" @click='editPer'>确 定</el-button>
            </template>
        </common-dialog>

        <!-- 移动端权限 -->
        <mobilePermission ref='mobilePermission'></mobilePermission>

        <!-- 复制权限 -->
        <common-dialog ref='copyPermission' :width="570" class='copyPhoneBox' @close='dialogClose("copyPermission", "copyForm")'>
            <template #title>
                <span class="title">复制{{ copyTit }}端用户权限</span>
            </template>
            <template #body>
                <div class='clearfix copyPhone'>
                    <div class='copyPermission'>
                        <el-form :model="copyForm" :rules='form_phoneRules' ref="copyForm" label-width="100px"
                            size="mini">
                            <el-form-item label="源用户" prop='yyh'>
                                <el-input v-model="copyForm.yyh" type='text' disabled>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="目标用户" prop='mbyh'>
                                <el-select v-model="copyForm.mbyh" multiple filterable remote reserve-keyword
                                    placeholder="请选择" :remote-method="remoteMethod_phone" :loading="loading"
                                    @focus='getFocus_phone'>
                                    <el-option v-for="item in copyOptions" :key="item.value" :label="item.label"
                                        :value="item.value">
                                        <div>{{ item.label }}</div>
                                        <span style='font-size: 12px;color:#dfdfdf'>{{ item.tit }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </template>
            <template #footer class='btn'>
                <el-button size="mini" @click='closeDialog("copyPermission", "copyForm")'>取 消</el-button>
                <el-button type="primary" size="mini" @click='dialogOk("copyPermission", "copyForm")'>确 定</el-button>
            </template>
        </common-dialog>

        <!-- 导入 -->
        <import-mould title='用户' ref='importMould' @importSuccess="importSuccess"></import-mould>
    </div>
</template>

<script>
    import {
        editPermissions,
        permissionsList,
        resetPwd,
        depList,
        userList,
        userListCopy,
        copyPermissions,
        userExport
    } from '@/api/userController'
    import {
        customFieldOther,
        fillFieldMess
    } from '@/api/customFieldController'
    import dynamicForm from '@/components/dynamicForm'
    import tableList from '../components/tableList.vue'
    import commonDialog from '../components/dialog.vue'
    import fileDownload from "js-file-download";
    import formLibrary from '@/components/formLibrary'
    import webEnumCode from './webEnumCode'
    import mobilePermission from './mobilePermission'
    import { productColumns } from '@/api/customFieldController'
    export default {
        components: {
            dynamicForm,
            tableList,
            commonDialog,
            formLibrary,
            mobilePermission
        },
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '' || value == undefined) {
                    callback(new Error('请输入密码'));
                } else if (value.length < 8) {
                    callback(new Error('密码至少8位'));
                } else {
                    if (this.resetPwd.qrmm !== '') {
                        this.$refs.resetPwd.validateField('qrmm');
                    }
                    let pRules = /^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/
                    if (!pRules.test(value)) {
                        callback(new Error('密码必须包含数字、大写、小写字母'))
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '' || value == undefined) {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.resetPwd.xmm) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var validatorAccount = (rule, value, callback) => {
                if(value === '') {
                    callback(new Error('账号 不能为空！'))
                } else if(value.length > 120) {
                    callback(new Error('超出字段长度'))
                } else {
                    callback()
                }
            }
            var validatorMobile = (rule, value, callback) => {
                if(value) {
                    if(value.length != 11 || value != Number(value)) {
                        callback(new Error('请输入正确手机号!'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            }
            var validatorName = (rule, value, callback) => {
                if(!this.checkSpecialKey(value)) {
                    callback(new Error('不能含有特殊字符!'))
                } else if(!value){
                    callback(new Error('姓名 不能为空'))
                } else if(value.length > 120) {
                    callback(new Error('超出字段长度'))
                } else {
                    callback()
                }
            }
            return {
                customFiledList: [],
                active: false,
                webPermissionLoading: false,
                config_checkAll: false,
                config_isIndeterminate: true,
                submenu: [],
                activeIndex: 0,
                config_group: [],
                config_btn: [],
                projectFormBatch: [],
                id: 0,
                menuIsIndeterminate:false,
                roleFlag:false,
                // 表单列表
                formDataList: {
                    formGroup: [{
                            label: 'name',
                            name: '姓名',
                            prop: '',
                            placeholder: '请输入姓名',
                            key: 'srk'
                        },
                        {
                            label: 'state',
                            name: '状态',
                            prop: '',
                            key: 'sel',
                            node: {
                                isRadio: true,
                                default: 0,
                                options: [{
                                        value: '',
                                        label: '全部'
                                    },
                                    {
                                        value: 0,
                                        label: '启用中'
                                    },
                                    {
                                        value: 1,
                                        label: '停用中'
                                    }
                                ]
                            }
                        },
                        {
                            label: 'account',
                            name: '账号',
                            prop: '',
                            placeholder: '请输入账号',
                            key: 'srk'
                        },
                        {
                            label: 'virtualType',
                            name: '虚拟用户',
                            prop: '',
                            key: 'sel',
                            node: {
                                isRadio: true,
                                default: '',
                                options: [{
                                        value: '',
                                        label: '全部'
                                    },
                                    {
                                        value: 1,
                                        label: '是'
                                    },
                                    {
                                        value: 0,
                                        label: '否'
                                    }
                                ]
                            }
                        },
                        {
                            label: 'role',
                            name: '角色',
                            prop: '',
                            key: 'sel',
                            node: {
                                isRadio: true,
                                default: '',
                                options: [{
                                        value: '',
                                        label: '全部'
                                    },
                                    {
                                        value: 1,
                                        label: '轻量-管理员'
                                    },
                                    {
                                        value: 2,
                                        label: '轻量-生产人员'
                                    },
                                    {
                                        value: 0,
                                        label: '用户账号管理员'
                                    }
                                ]
                            }
                        },
                    ],
                    searchForm: {
                        name: '',
                        state: '', //停用中:1 启用中:0
                        account: '',
                        virtualType: '', //是:1 不是:0
                        role: '', //轻量-管理员:0  轻量-生产人员:1   用户账号管理员:2
                        limit: 10,
                        page: 1
                    },
                    formSet: false
                },
                // 列配置
                disposeGroup: [],
                tableGroup: [],
                //创建用户表单
                createForm: {
                    account: '',
                    name: '',
                    mobile: '',
                    role: [],
                    depName: [],
                    virtualType: 0
                },
                // 重置密码表单
                resetPwd: {
                    id: '',
                    name: '',
                    account: '',
                    xmm: '',
                    qrmm: ''
                },
                // 是否虚拟用户
                isVirtualUserOptions: [{
                        label: '是',
                        value: 1
                    },
                    {
                        label: '否',
                        value: 0
                    }
                ],
                // 表单规则
                form_userRules: {
                    account: [{
                        required: true,
                        trigger: 'change',
                        validator: validatorAccount
                    }],
                    role: [{
                        required: true,
                        message: '角色 不能为空!',
                    }],
                    mobile: [{
                        validator: validatorMobile,
                        trigger: 'blur'
                    }],
                    name: [{
                        required: true,
                        validator: validatorName,
                        trigger: 'change'
                    }]
                },
                form_pwdRules: {
                    xmm: [{
                        validator: validatePass,
                        trigger: 'change',
                        required: true
                    }],
                    qrmm: [{
                        validator: validatePass2,
                        trigger: 'change',
                        required: true
                    }],
                },
                form_phoneRules: {
                    mbyh: [{
                        required: true,
                        message: '请选择目标用户',
                        trigger: 'blur'
                    }]
                },
                // 新增成功
                newSuccessData: {
                    user: '',
                    name: '',
                    pwd: 'NKHS5f7J'
                },
                createrUserTitle: '创建用户',
                loading: false,
                selLoading: false,
                roleItems: {
                    options: [{
                            label: "轻量-管理员",
                            value: '1'
                        },
                        {
                            label: "轻量-生产人员",
                            value: '2'
                        },
                        {
                            label: "用户账号管理员",
                            value: '0'
                        },
                    ],
                    states: [{
                            label: "轻量-管理员",
                            value: '1'
                        },
                        {
                            label: "轻量-生产人员",
                            value: '2'
                        },
                        {
                            label: "用户账号管理员",
                            value: '0'
                        },
                    ],
                    list: [],
                    num: 0
                },
                depItems: {
                    options: [],
                    list: [],
                    num: 0
                },
                //复制移动端用户权限
                copyForm: {
                    yyh: '',
                    mbyh: []
                },
                copyOptions: [],
                copyType: null,
                disabled: true,
                ids: '',
                copyTit: '',
                defaultData: [], // 自定义字段值
                customFiledData: [],
                customState: true, // 判断单选/复选 选值是否正确
                customErrorLabel: '',// 选值错误提示语
                // 关联属性信息
                relevanceProp: [],
                uploadFlag: true,
                editId: null
            }
        },
        watch: {
            disabled(flag) {
                //当表格数据为空时 列配置和表头无自定义字段信息
                if (flag) {
                    this.tableGroup = this.utils.filterCustomFields(this.tableGroup)
                    this.disposeGroup = this.utils.filterCustomFields(this.disposeGroup)
                }
            }
        },
        mounted() {
            this.roleItems.list = this.roleItems.states.map((item, i) => {
                return {
                    value: `${item.value}`,
                    label: `${item.label}`
                };
            });
            this.getDepList({
                limit: 100,
                page: 1,
                name: ''
            })
            this.getProductColumns({
                type: 'user'
            }).then(()=>{
                this.$refs.tableList.getUserList(this.formDataList.searchForm)
            })
        },
        methods: {
            //==================== 接口
            // 权限列表
            getPermissionsList(data) {
                this.webPermissionLoading = true
                permissionsList(data).then(res => {
                    if (res.code == 200) {
                        this.config_group = [] //打开不同账户先置空
                        this.submenu = []
                        this.projectFormBatch = JSON.parse(res.data.menu)
                        //找到生产管理工单对应的筛选配置
                        let targetIndex = this.projectFormBatch.findIndex(i => i.permCode === "production.management")
                        let subIndex = this.projectFormBatch[targetIndex].submenu.findIndex(i => i.permCode === "project")
                        this.projectFormBatch[targetIndex].submenu[subIndex].filtrateConfig.forEach(item => {
                            if (item.blPerm) this.config_group = [...this.config_group, item.permCode]
                        })
                        this.getSubmenu(this.projectFormBatch[this.activeIndex].submenu, this
                            .activeIndex) //默认选中 生产管理--工单
                    }
                    this.webPermissionLoading = false
                })
            },
            
            //编辑权限
            getEditPermissions_web(data) {
                editPermissions(data).then(res => {
                    if (res.code == 200) {
                        this.projectFormBatch = JSON.parse(res.data)
                        this.$store.commit('setPermissionList', JSON.parse(res.data))
                        this.$refs.webPermission.closeDialog()
                        this.utils.showMsg('设置成功', 'success')
                    }
                })
            },
            // 重置密码
            getResetPwd() {
                let d = {
                    id: this.resetPwd.id,
                    pwd: this.resetPwd.xmm,
                    confirmPwd: this.resetPwd.qrmm
                }
                this.$refs.resetPwd.resetFields()
                this.loading = true;
                resetPwd(d).then(res => {
                    if (res.code == 200) {
                        this.utils.showMsg('重置密码成功', 'success')
                        this.loading = false
                    }
                })
            },
            // 权限复制目标用户列表
            getUserListCopy(data) {
                userListCopy(data).then(res => {
                    this.copyOptions = []
                    if (res.code == 200) {
                        res.data.map(item => {
                            this.copyOptions.push({
                                value: item.id,
                                label: item.name,
                                tit: this.enumCon.roleEscape(item.role)
                            })
                        })
                    }
                })
            },
            // 复制权限
            getCopyPermissions(data) {
                copyPermissions(data).then(res => {
                    if (res.code == 200) {
                        this.utils.showMsg('权限复制成功', 'success')
                    }
                })
            },
            //移动端权限
            emitPermission(row){
                this.$refs.mobilePermission.switchOn(row.id)
            },
            // 导出
            getUserExport() {
                this.$refs.tableList.exportTable('用户' + new Date().dateFormat('yyyyMMddhhmmss'))
            },
            // 导入
            importModel() {
                let obj = {
                    type: 'user',
                    importUrl: '/user/excel_import',
                    isCover:false
                }
                this.$refs.importMould.openDialog(obj)
            },
            // 导入成功
            importSuccess() {
                this.$refs.tableList.getUserList(this.formDataList.searchForm)
            },
            // 自定义字段
            getCustomFieldOther(way) {
                customFieldOther({type: 'user'}).then(res => {
                    this.customFiledList = []
                    this.relevanceProp = []
                    if(res.code == 200) {
                        // 自定义字段数据
                        res.data.map(item => {
                            item.customFieldMess.objectsValue = item.objectsValue
                            this.customFiledList.push(item.customFieldMess)
                        })
                        // 添加自定义字段的校验规则(是否必填)
                        this.customFiledList.map(item => {
                            let r = item.hidden
                            item.hidden = r.replace(/\${产品./g, 'formItemData["').replace(/\}/g, '"]').replace(/\${用户信息/g,'formItemData')
                            item.id = item.id + ''
                            let obj = {}
                            if(JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                                obj[item.id] = [{
                                    required: true,
                                    message: item.chineseName + '不能为空'
                                }]
                            }else if(item.fieldType == 'inputNumber'){
                                const numberRule = (rule, v, callback) => {
                                    let tempValue = ''
                                    let index = String(this.createForm[item.id]).indexOf('.')
                                    tempValue = index != -1 ? String(this.createForm[item.id]).slice(0,index) : String(this.createForm[item.id])
                                    if (!this.createForm[item.id] && item.isRequired) {
                                        return callback(new Error(`${item.chineseName}不能为空！`));
                                    }else if(tempValue.length > 10){
                                        return callback(new Error('整数位最多支持10位数字'));
                                    }else if(this.createForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.createForm[item.id]))){
                                        return callback(new Error('小数点后最多保留6位数字'));
                                    }else {
                                        callback()
                                    }
                                }
                                obj[item.id] = [{
                                    validator: numberRule,
                                    trigger:'blur'
                                }]
                            }
                            this.form_userRules = Object.assign(this.form_userRules, obj)
                            if(item.fieldType == 'relevanceProp') {
                                this.relevanceProp.push({
                                    id: item.id,
                                    objectFieldId: item.objectFieldId,
                                    type: item.correlationField
                                })
                            }
                        })
                        this.hiddenRule('')
                        this.$refs[way].openDialog()
                    }
                })
            },
            // 列配置
            getProductColumns: async function(data){
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                            index:'80',
                            account:'100',
                            name:'100',
                            mobile:'100',
                            virtualType:'70',
                            state:'70'
                        }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'user',
                    configureList
                }).then(()=>{
                    this.$refs.tableList.changeLayout() //防止改变table列配置出现抖动
                })
            },
            //表格操作
            getDepList(v) {
                depList(v).then(res => {
                    this.selLoading = false
                    if (res.code == 200) {
                        this.depItems.options = res.data.records.map(item => {
                            return {
                                value: `${item.id}`,
                                label: `${item.name}`
                            };
                        });
                    }
                })
            },
            //======================按钮事件
            // 表格行操作
            tableSet(obj) {
                this.createrUserTitle = '编辑用户'
                this.editId = obj.node.id
                this.createForm = {
                    account: '',
                    name: '',
                    mobile: '',
                    role: [],
                    depName: [],
                    virtualType: 0
                }
                this.roleFlag = obj.node.role.indexOf('0') != -1
                for (let key in this[obj.formName]) {
                    this[obj.formName][key] = obj.node[key]
                }
                if (obj.formName == 'createForm') {
                    this.customFiledData = []
                    this.defaultData = []
                    this.createForm.id = obj.node.id
                    this.createForm.role = obj.node.role.split(',')
                    if (obj.node.depId) {
                        this.createForm.depName = (obj.node.depId).split(',')
                    } else {
                        this.createForm.depName = []
                    }
                    if(obj.node.customFieldVos != null) {
                        obj.node.customFieldVos.map(item => {
                            this.$set(this.createForm, item.customFieldId, item.value)
                            this.customFiledData.push({
                                customFieldId: item.customFieldId,
                                value: item.value
                            })
                            this.defaultData.push({
                                customFieldId: item.customFieldId,
                                value: item.value
                            })
                        })
                    }
                    this.getCustomFieldOther(obj.name)
                } else {
                    this.$refs[obj.name].openDialog()
                }
            },
            // 新增用户
            createUser(way) {
                this.createrUserTitle = '创建用户'
                this.createForm = {
                    account: '',
                    name: '',
                    mobile: '',
                    role: [],
                    depName: [],
                    virtualType: 0
                }
                this.defaultData = []
                this.getCustomFieldOther(way)
            },
            // web端权限
            webPermission(v, row, t) {
                this.$refs[v].openDialog()
                this.id = row.id
                if (v == 'webPermission') {
                    this.activeIndex = 1
                    this.getPermissionsList({
                        type: 0,
                        userId: row.id
                    })
                }
                if (v == 'copyPermission') {
                    this.copyType = t
                    this.copyForm.mbyh = []
                    let pro = this.enumCon.roleEscape(row.role)
                    this.copyForm.yyh =
                        row.name + ' | ' + pro
                    t == 1 ? this.copyTit = '移动' : this.copyTit = 'web'
                }
            },
            // 表格内容勾选
            tableListChecked(arr) {
                
            },
            // 角色下拉
            remoteMethod_role(query) {
                this.loading = true;
                setTimeout(() => {
                    this.loading = false;
                    this.roleItems.options = this.roleItems.list.filter(item => {
                        return item.label.toLowerCase()
                            .indexOf(query.toLowerCase()) > -1;
                    });
                }, 200);
            },
            // 部门下拉
            getFocus(v) {
                if (v == 'role') {
                    if (this.roleItems.num == 0) {
                        this.remoteMethod_role('')
                        this.roleItems.num++
                    }
                } else {
                    if (this.depItems.num == 0) {
                        this.remoteMethod_dep('')
                        this.depItems.num++
                    }
                }

            },
            remoteMethod_dep(query) {
                this.selLoading = true;
                let obj = {
                    limit: 100,
                    page: 1,
                    name: query
                }
                this.getDepList(obj)
            },
            // 查看日志
            viewImportLog() {
                this.$router.push({
                    path: '/stmConfiguration/user/loadLog',
                    query: {
                        name: '用户'
                    }
                })
            },
            //点击查询获取表单数据
            getFormData(val) {
                this.$refs.tableList.getUserList(val)
            },
            // 移动端权限复制事件
            getFocus_phone() {
                if (this.copyForm.mbyh.length == 0) {
                    this.remoteMethod_phone('')
                }
            },
            remoteMethod_phone(query) {
                this.getUserListCopy({
                    name: query
                })
            },

            // ======================弹框操作
            // 关闭新增用户弹框
            closeDialog(v, f) {
                this.$refs[v].closeDialog()
            },
            dialogClose(d, f) {
                if(this.$refs.formLibrary != undefined) {
                    this.$refs.formLibrary.map(k => {
                        k.removeData('cancle')
                    })
                }
                this.$refs[f].resetFields()
            },
            // 弹框确认
            dialogOk(v, f) {
                this.$refs[f].validate((valid) => {
                    if (valid) {
                        let obj = {
                            account: this.createForm.account,
                            name: this.createForm.name,
                            mobile: this.createForm.mobile,
                            role: this.createForm.role,
                            depId: this.createForm.depName,
                            virtualType: this.createForm.virtualType
                        }
                        obj.role = obj.role.join(',')
                        obj.depId = obj.depId.join(',')
                        if (v == 'createUser') {
                            this.newSuccessData.user = this.createForm.account
                            this.newSuccessData.name = this.createForm.name
                            let customData = []
                            for(let key in this.createForm) {
                                if(Number(key)) {
                                    this.customFiledList.find(item => {
                                        if(
                                            item.id == key &&
                                            this.createForm[key] !== '' &&
                                            this.createForm[key] != '[]' &&
                                            this.createForm[key] != '{}' &&
                                            this.createForm[key] != null &&
                                            !(Array.isArray(this.createForm[key]))
                                        ) {
                                            customData.push({
                                                customFieldId: item.id,
                                                value: this.createForm[key]
                                            })
                                        }
                                        if(Array.isArray(this.createForm[key]) && this.createForm[key].length > 0) {
                                            customData.push({
                                                customFieldId: item.id,
                                                value: this.createForm[key]
                                            })
                                        }
                                    })
                                }
                            }
                            obj.customFieldVos = customData

                            // 关联对象后，判断单选框/复选框关联过来的值是否存在
                            this.customState = true
                            this.customErrorLabel = ''
                            this.customFiledList.map(item => {
                                // 单选框
                                if(item.fieldType == 'selectRadio') {
                                    if(this.createForm[item.id] != '' && this.createForm[item.id] != undefined) {
                                        let s = JSON.parse(item.checkBox).find(res => { return this.createForm[item.id] == res.value })
                                        if(s == undefined) {
                                            this.customState = false
                                            this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                        }
                                    }
                                }
                                // 复选框
                                if(item.fieldType == 'selectChecked') {
                                    if(this.createForm[item.id] != '' && this.createForm[item.id] != undefined && this.createForm[item.id] != '[]') {
                                        JSON.parse(this.createForm[item.id]).map(k => {
                                            let s = JSON.parse(item.checkBox).find(res => { return res.value == k })
                                            if(s == undefined) {
                                                this.customState = false
                                                this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                            }
                                        })
                                    }
                                }
                            })
                            if(this.uploadFlag) {
                                this.createForm = {
                                    account: '',
                                    name: '',
                                    mobile: '',
                                    role: [],
                                    depName: [],
                                    virtualType: 0,
                                }
                                if(this.$refs.formLibrary != undefined) {
                                    this.$refs.formLibrary.map(k => {
                                        k.removeData('ok')
                                    })
                                }
                                this.$nextTick(() => {
                                    if (this.createrUserTitle == '创建用户') {
                                        this.$refs[v].closeDialog()
                                        this.$refs.tableList.getUserHandle(obj, 'create')
                                        return
                                    } else {
                                        obj.id = this.editId,
                                        this.$refs[f].resetFields()
                                        this.$refs.tableList.getUserHandle(obj, 'edit')
                                    }
                                })
                            } else {
                                this.utils.showMsg('正在上传，请稍后', 'warning')
                            }
                        }
                        if (v == 'newPwd') {
                            this.getResetPwd()
                        }
                        if (v == 'copyPermission') {
                            let ids = this.copyForm.mbyh.join(',')
                            this.getCopyPermissions({
                                id: this.id,
                                type: this.copyType,
                                toUserId: ids
                            })
                        }
                        if(this.uploadFlag) {
                            this.$refs[v].closeDialog()
                        }
                    } else {
                        return false;
                    }
                });
            },
            // 创建成功，打开弹窗显示新用户账号密码
            createSuccess() {
            //     this.$refs.newUser.openDialog()
            },
            // 新建成功弹框
            newSuccess(v) {
                this.newSuccessData.user = ''
                this.newSuccessData.name = ''
                this.$refs.createForm.resetFields()
                this.$refs[v].closeDialog()
            },
            //一级菜单勾选框状态改变事件
            firstMenuChange(item){
                item.submenu.forEach(e =>{  //一级菜单下的所有子级菜单随着勾选框的状态变化而变化 
                    if(e.permTitle == '工单') {
                        this.config_checkAll = item.blPerm
                        this.handleCheckAllChange(item.blPerm)
                    }
                    e.blPerm = item.blPerm
                })
            },
            //例如：工单模块false时其内部的所有其它路由权限都应该为false，禁止浏览器输入url进入该页面
            checkChange(item, index) {
                if(item.permTitle == '工单'){ //筛选配置勾选框状态随着工单勾选框状态变化而变化
                    this.config_checkAll = item.blPerm
                    this.handleCheckAllChange(item.blPerm)
                }
                if (this.submenu.length) {
                    let menuState = this.submenu.every(e => {
                        return e.blPerm == false
                    })
                    if(!menuState) {
                        // this.$refs['production.management'][0].indeterminate = true
                    }
                    this.projectFormBatch[this.activeIndex].blPerm = !menuState
                }
                this.projectFormBatch[this.activeIndex].submenu[index].routerMenu.forEach(i => {
                    i.blPerm = item.blPerm
                })
            },
            //编辑权限--确定
            editPer() {
                this.config_btn.forEach(i => {
                    i.blPerm = this.config_group.indexOf(i.permCode) != -1
                })
                // 一级菜单勾选框状态随着二级菜单变化 -- 
                // 二级菜单全为false时一级菜单false，二级菜单有一个为true，一级菜单为true，样式bug后期修改
                if (this.submenu.length) {
                    let menuState = this.submenu.every(e => {
                        return e.blPerm == false
                    })
                    this.projectFormBatch[this.activeIndex].blPerm = !menuState
                }
                const targetArr = this.config_btn.filter(i => i.permCode === 'button.createOrder' || i.permCode === 'button.edit')
                const updatePermissionQueries = targetArr.map(i => {
                    return {
                        permCode:webEnumCode[i.permCode],
                        propertyName:'blPerm',
                        propertyValue:i.blPerm
                    }
                })
                let menuIds = JSON.stringify(this.projectFormBatch)
                this.getEditPermissions_web({
                    id: this.id,
                    menuIds,
                    type: 0,
                    updatePermissionQueries
                })
            },


            //点击一级菜单获取二级菜单数据
            getSubmenu(menu, index) {
                let targetMenu = menu.find(i => i.filtrateConfig)
                this.config_btn = targetMenu !== undefined ? targetMenu.filtrateConfig : []
                this.submenu = menu
                this.activeIndex = index
                this.config_checkAll = this.config_group.length === this.config_btn.length
                this.config_isIndeterminate = this.config_group.length > 0 && this.config_group.length < this.config_btn
                    .length;
            },
            //表单配置全选
            handleCheckAllChange(val) {
                this.submenu.forEach(e =>{ //二级菜单工单勾选框状态和筛选配置所有勾选框状态相互影响
                    if(e.permTitle == '工单'){
                        e.blPerm = val
                    }
                })
                const data = this.config_btn.map(item => {
                    return item.permCode
                })
                this.config_group = val ? data : [];
                this.config_isIndeterminate = false;
            },
            //筛选配置
            handleCheckedConfig(value) {
                let checkedCount = value.length;
                this.config_checkAll = checkedCount === this.config_btn.length;
                this.config_isIndeterminate = checkedCount > 0 && checkedCount < this.config_btn.length;
            },
            formReset(obj) {
                for (let key in obj) {
                    Array.isArray(obj[key]) ? obj.key = [] : obj.key = '';
                }
                obj.virtualType = '2'
                return obj
            },
            exportDisabled(v) {
                this.disabled = v
            },
            // 新建用户默认密码
            defaultPassWord(p, t) {
                if(t != 'edit') {
                    this.$refs.newUser.openDialog()
                }
                this.newSuccessData.pwd = p
            },
            // 校验特殊字符
            checkSpecialKey(str) {
                var specialKey = "[`~@!#$^&*()=|{}':;'\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
                for (var i = 0; i < str.length; i++) {
                    if (specialKey.indexOf(str.substr(i, 1)) != -1) {
                        return false;
                    }
                }
                return true;
            },

            // 自定义表单项数据--表单子组件传递的值
            formItemHandle(d) {
                // 子组件的值赋给表单
                this.$set(this.createForm, d.name, d.value)
                // 操作的是关联对象
                if(d.relevanceObject != undefined) {
                    if(d.relevanceObject.id) {
                        let data = {
                            id: d.relevanceObject.id,
                            type: d.relevanceObject.businessObject
                        }
                        this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
                    } else {
                        this.customFiledList.map(item => {
                            if(item.objectFieldId == d.name) {
                                this.createForm[item.id] = ''
                                this.defaultData.map(k => {
                                    if(k.customFieldId == item.id || k.customFieldId == d.name) {
                                        k.value = ''
                                    }
                                })
                            }
                        })
                        for(let key in this.createForm) {
                            let ind = this.defaultData.findIndex(res => {return res.customFieldId == key })
                            if(ind != -1) {
                                this.$set(this.defaultData, ind, { customFieldId: key, value: this.createForm[key] })
                            } else {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.createForm[key]
                                })
                            }
                        }
                    }
                }
            },
            // 关联对象-字段信息
            getFillFieldMess(data, fillRule, n) {
                fillFieldMess(data).then(res => {
                    this.defaultData = []
                    for(let key in this.createForm) {
                        if(Number(key)) {
                            this.defaultData.push({
                                customFieldId: key,
                                value: this.createForm[key]
                            })
                        }
                    }
                    if(res.code == 200) {
                        // 如果该条数据有自定义字段
                        if(res.data.customFieldVos != null) {
                            /* 
                                遍历关联对象的填充规则
                                遍历该条数据的自定义字段列表
                                将填充规则中的来源值(from) 赋给 指定控件(to)
                            */
                            fillRule.map(item => {
                                let dataArr = []
                                let f = res.data.customFieldVos.find(res => { return res.customFieldId == item.from })
                                if(f != undefined) {
                                    res.data.customFieldVos.map(k => {
                                        if(k.customFieldId == item.from) {
                                            this.createForm[item.to] = k.value
                                            this.defaultData = this.defaultData.filter(j => j.customFieldId != item.to)
                                            this.defaultData.push({
                                                customFieldId: item.to,
                                                value: k.value
                                            })
                                        }
                                    })
                                } else {
                                    this.createForm[item.to] = ''
                                    this.defaultData.map(k => {
                                        if(k.customFieldId == item.to) {
                                            let d = this.customFiledList.find(res => { return res.id == item.to })
                                            if(d.fieldType == 'picture' || d.fieldType == 'upload' || d.fieldType == 'selectChecked') {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: "[]"
                                                })
                                            } else { 
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: ""
                                                })
                                            }
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: k.value
                                            })
                                        }
                                    })
                                    this.defaultData = dataArr
                                }
                            })
                        } else {
                            fillRule.map(item => {
                                let dataArr = []
                                this.createForm[item.to] = ''
                                this.defaultData.map(k => {
                                    if(k.customFieldId == item.to) {
                                        let d = this.customFiledList.find(res => { return res.id == item.to })
                                        if(d.fieldType == 'picture' || d.fieldType == 'upload' || d.fieldType == 'selectChecked') {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: "[]"
                                            })
                                        } else { 
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: ""
                                            })
                                        }
                                    } else {
                                        dataArr.push({
                                            customFieldId: k.customFieldId,
                                            value: k.value
                                        })
                                    }
                               })
                               this.defaultData = dataArr
                            })
                        }
                        // 关联属性赋值
                        this.relevanceProp.map(item => {
                            if(item.objectFieldId == n) {
                                this.createForm[item.id] = res.data[item.type]
                                this.defaultData = this.defaultData.filter(j => j.customFieldId != item.id)
                                this.defaultData.push({
                                    customFieldId: item.id,
                                    value: res.data[item.type]
                                })
                            }
                        })
                    }
                })
            },
            // 自定义隐藏设置--隐藏条件触发
            hiddenRule(d) {
                let formItemData = {
                    '账号': this.createForm.account,
                    '姓名': this.createForm.name,
                    '手机号': this.createForm.mobile,
                    '角色': this.customData(this.createForm.role, this.roleItems.options),
                }
                this.customFiledList.map(item => {
                    if(formItemData[item.chineseName] == undefined) {
                        if(this.createForm[item.id] != undefined) {
                            formItemData[item.chineseName] = this.createForm[item.id]
                        } else {
                            formItemData[item.chineseName] = ''
                        }
                    }
                })
                let state = null
                try {
                    state = !eval(d.hidden)
                } catch {
                    state = true
                }
                //必填项字段若是被隐藏不校验
                if (this.form_userRules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                            d.isRequired = state
                        }
                    }else{
                        this.form_userRules[d.id][0].required = state
                    }
                }
                return state
            },
            requireRsterisk(d) {
                if (this.form_userRules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        return JSON.parse(d.fieldAttribute).required || false
                    }else{
                        return this.form_userRules[d.id][0].required || false
                    }
                }
            },
            customData(v, data) {
                if(Number(v)) {
                    let id = ''
                    data.map(item => {
                        if(item.value == v) {
                            id = item.label
                        }
                    })
                    return id
                } else {
                    return v
                }
            },
            // 附件/图片上传是否完成
            uploadProgress(s) {
                this.uploadFlag = s
            },
            virtualUserChange() {
                this.$nextTick(() => {
                    this.$refs.virtual.blur()
                })
            }
        }
    }
</script>

<style lang="less" scoped>
    .outPutStatistics {
        overflow: auto;

        .dialogBody {
            max-height: 302px;
            overflow: hidden auto;
            border: 1px solid #edeef3;
            background: #fbfbfb;
            width: 700px;

            .formArea_user {
                width: 480px;
                padding: 20px 0 20px 50px;

                /deep/ .el-select {
                    width: 100%;
                }
            }
        }

        .webPermission {
            p {
                color: #666;
                font-size: 12px;
                margin-bottom: 8px;
            }

            .el-empty{
                height: 100%;
            }

            .checkGroup_permission {
                border: 1px solid #f2f2f2;

                .menu_item {
                    .menu_th {
                        height: 48px;
                        background: #fafafa;
                        padding: 17px 20px;
                        border-bottom: 1px solid #f2f2f2;
                        border-right: 1px solid #f2f2f2;
                        color: rgba(0, 0, 0, .85);
                        font-size: 12px;
                    }

                    .menu_tb {
                        height: 310px;
                        overflow-y: scroll;

                        .menu_tb_list {
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            padding: 0 20px;
                            height: 56px;
                            border-bottom: 1px solid #f2f2f2;
                            cursor: pointer;

                            .tag {
                                display: inline-block;
                                font-size: 14px;
                            }
                        }

                        .menu_tb_list.config {
                            background: #fafafa;

                            span {
                                font-size: 12px;
                                color: rgba(0, 0, 0, .85);
                                margin-right: 10px;
                            }

                            justify-content: start;
                        }

                        .menu_tb_list_group {
                            padding: 17px 10px 0;

                            .el-checkbox-group {
                                display: flex;
                                flex-wrap: wrap;
                                font-size: 12px;

                                .el-checkbox {
                                    width: 45%;
                                    margin-bottom: 17px;
                                }

                                .el-checkbox:nth-child(odd) {
                                    margin-right: 20px;
                                }

                                .el-checkbox:nth-child(even) {
                                    margin-right: 0;
                                }
                            }
                        }

                        .active {
                            background: #f0fbfb;
                        }
                    }

                    /deep/ .el-checkbox__label {
                        font-size: 12px;
                    }

                    /deep/ .el-checkbox__input.is-checked+.el-checkbox__label {
                        color: rgba(0, 0, 0, .85);
                    }
                }
            }
        }

        .dialogBody_newpwd {
            border: 1px solid #edeef3;
            background: #fbfbfb;
            padding: 20px 80px;
        }

        .newOkBox {
            /deep/ .el-dialog__header {
                display: flex;
                align-items: center;
                font-size: 14px;
            }

            /deep/ .el-dialog__body {
                padding: 0 58px 10px;
                font-size: 13px;
            }

            .newSuccess {
                color: #52c41a;
                font-size: 22px;
                margin-right: 16px;
            }
        }

        .copyPhoneBox {
            .copyPhone {
                border: 1px solid #edeef3;
                padding: 20px 30px 10px 50px;
                height: 150px;
                overflow: auto;
                background: #fbfbfb;
            }
        }

        /deep/ .searchContent {
            border: none
        }

        /deep/ .el-dialog__footer {
            text-align: center;

            button {
                width: 100px;
            }
        }

        /deep/ .el-select {
            width: 100%;
        }
    }
</style>